#!/bin/sh

printf "Content-type: application/json\r\n\r\n"

HOSTNAME=$(hostname)
FW_VERSION=$(cat /tmp/sd/yi-hack/version)
HOME_VERSION=$(cat /home/app/.appver)
MODEL_SUFFIX=$(cat /tmp/sd/yi-hack/model_suffix)
SERIAL_NUMBER=$(dd bs=1 count=20 skip=656 if=/tmp/mmap.info 2>/dev/null | cut -c1-20)
LOCAL_TIME=$(date)
UPTIME=$(cat /proc/uptime | cut -d ' ' -f1)
LOAD_AVG=$(cat /proc/loadavg | cut -d ' ' -f1-3)
TOTAL_MEMORY=$(free -k | awk 'NR==2{print $2}')
FREE_MEMORY=$(free -k | awk 'NR==2{print $4+$6+$7}')
FREE_SD=$(df /tmp/sd/ | grep mmc | awk '{print $5}' | tr -d '%')
if [ -z "$FREE_SD" ]; then
    FREE_SD="N/A"
else
    FREE_SD=$((100-$FREE_SD))%
fi

LOCAL_IP=$(ifconfig wlan0 | awk '/inet addr/{print substr($2,6)}')
NETMASK=$(ifconfig wlan0 | awk '/inet addr/{print substr($4,6)}')
GATEWAY=$(route -n | awk 'NR==3{print $2}')
MAC_ADDR=$(ifconfig wlan0 | awk '/HWaddr/{print substr($5,1)}')
WLAN_ESSID=$(iwconfig wlan0 | grep ESSID | cut -d\" -f2)
WLAN_STRENGTH=$(cat /proc/net/wireless | awk 'END { print $3 }' | sed 's/\.$//')

# Yeah, it's pretty ugly.. but hey, it works.

printf "{\n"
printf "\"%s\":\"%s\",\n" "hostname"        "$HOSTNAME"
printf "\"%s\":\"%s\",\n" "fw_version"      "$FW_VERSION"
printf "\"%s\":\"%s\",\n" "home_version"    "$HOME_VERSION"
printf "\"%s\":\"%s\",\n" "model_suffix"    "$MODEL_SUFFIX"
printf "\"%s\":\"%s\",\n" "serial_number"   "$SERIAL_NUMBER"
printf "\"%s\":\"%s\",\n" "local_time"      "$LOCAL_TIME"
printf "\"%s\":\"%s\",\n" "uptime"          "$UPTIME"
printf "\"%s\":\"%s\",\n" "load_avg"        "$LOAD_AVG"
printf "\"%s\":\"%s\",\n" "total_memory"    "$TOTAL_MEMORY"
printf "\"%s\":\"%s\",\n" "free_memory"     "$FREE_MEMORY"
printf "\"%s\":\"%s\",\n" "free_sd"         "$FREE_SD"

printf "\"%s\":\"%s\",\n" "local_ip"        "$LOCAL_IP"
printf "\"%s\":\"%s\",\n" "netmask"         "$NETMASK"
printf "\"%s\":\"%s\",\n" "gateway"         "$GATEWAY"
printf "\"%s\":\"%s\",\n" "mac_addr"        "$MAC_ADDR"
printf "\"%s\":\"%s\",\n" "wlan_essid"      "$WLAN_ESSID"
printf "\"%s\":\"%s\" \n" "wlan_strength"   "$WLAN_STRENGTH"

printf "}"
